package com.luck.pf.util;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Base64B {
	public static void main(String[] args) {
		if (args.length == 2) {
			String string = Base64B.encode(args[0]);
			Base64B.decode(string, args[1]);
		} else
			System.out.println("usage: java Base64 inputFile outputFile");
	}
	//编码
	public static String encode(String fileName) {
		String string = null;
		try {
			InputStream in = new FileInputStream(fileName);
			// in.available()返回文件的字节长度
			byte[] bytes = new byte[in.available()];
			// 将文件中的内容读入到数组中
			in.read(bytes);
			string = new BASE64Encoder().encode(bytes);
			in.close();
		} catch (FileNotFoundException fe) {
			fe.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		return string;
	}
	//解码
	public static void decode(String string, String fileName) {
		try {
			// 解码，然后将字节转换为文件
			byte[] bytes = new BASE64Decoder().decodeBuffer(string);
			ByteArrayInputStream in = new ByteArrayInputStream(bytes);
			byte[] buffer = new byte[1024];
			FileOutputStream out = new FileOutputStream(fileName);
			int bytesum = 0;
			int byteread = 0;
			while ((byteread = in.read(buffer)) != -1) {
				bytesum += byteread;
				out.write(buffer, 0, byteread);
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
}
